import type { Env } from '../../types';
import { saveShareText, getShareTextList } from '../textApi';
import { createErrorResponse } from '../../utils/errorHandler';

export async function handleTextApiRequest(
  request: Request,
  url: URL,
  env: Env
): Promise<Response> {
  const path = url.pathname;
  const method = request.method;

  switch (method) {
    case 'GET':
      if (path === '/api/text/list') {
        return await getTextList(request, url, env);
      }
      break;

    case 'POST':
      if (path === '/api/text/save') {
        return await postText(request, url, env);
      }
      break;

    case 'DELETE':
      if (path === '/api/text/delete') {
        return await deleteText(request, url, env);
      }
      break;

    default:
  }
  return createErrorResponse('Not found', 404);
}

/**
 * 获取文本列表
 * @param request 
 * @param url 
 * @param env 
 * @returns 
 */
async function getTextList(request: Request, url: URL, env: Env): Promise<Response> {
  const result = await getShareTextList(env);
  if (!result.success) {
    return createErrorResponse(result.error || 'Failed to get text list', 500);
  }
  return new Response(JSON.stringify(result.data), { headers: { 'content-type': 'application/json' } });

}

/**
 * 保存文本

 * @param request 
 * @param url 
 * @param env 
 * @returns 
 */
async function postText(request: Request, url: URL, env: Env): Promise<Response> {
  try {
    const { content, userId, groupId, fingerprintId }: any = await request.json();

    if (!content || content.trim() === '') {
      return createErrorResponse('Content cannot be empty', 400);
    }

    const result = await saveShareText(env, content, userId || 1, groupId || 1, fingerprintId || 'unknown');
    if (!result.success) {
      return createErrorResponse(result.error || 'Failed to save text', 500);
    }

    return new Response(JSON.stringify(result.data), { headers: { 'content-type': 'application/json' }, status: 201 });
  } catch (error) {
    console.error('Error saving text:', error);
    return createErrorResponse('Invalid request body', 400);
  }
}


async function deleteText(request: Request, url: URL, env: Env): Promise<Response> {
  return new Response('Delete text', { status: 200 });
}
